package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.time.LocalDateTime;

@Slf4j
@Aspect
@Component
public class AutoFillAspect {
    //公共切入点
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    public void autoFillPointCut(){}
    //前置通知
    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        //获取操作类型
        MethodSignature methodSignature= (MethodSignature) joinPoint.getSignature();
        AutoFill autoFill=methodSignature.getMethod().getAnnotation(AutoFill.class);
        OperationType operationType=autoFill.value();
        //获取操作对象
        Object[] args = joinPoint.getArgs();
        if (args.length==0){
            return;
        }
        Object entity = args[0];
        //准备数据
        LocalDateTime now=LocalDateTime.now();
        Long empId= BaseContext.getCurrentId();
        //根据操作类型进行数据填充
        if(operationType== OperationType.INSERT){
            entity.getClass().getMethod(AutoFillConstant.SET_CREATE_TIME,LocalDateTime.class).invoke(entity,now);
            entity.getClass().getMethod(AutoFillConstant.SET_UPDATE_TIME,LocalDateTime.class).invoke(entity,now);
            entity.getClass().getMethod(AutoFillConstant.SET_CREATE_USER,Long.class).invoke(entity,empId);
            entity.getClass().getMethod(AutoFillConstant.SET_UPDATE_USER,Long.class).invoke(entity,empId);
        }else if(operationType==OperationType.UPDATE){
            entity.getClass().getMethod(AutoFillConstant.SET_UPDATE_TIME,LocalDateTime.class).invoke(entity,now);
            entity.getClass().getMethod(AutoFillConstant.SET_UPDATE_USER,Long.class).invoke(entity,empId);
        }
    }

}
